<!--
 *Author：jxx
 *Date：{Date}
 *Contact：283591387@qq.com
 *业务请在@/extension/mes/mes/ProductProcessReport.jsx或ProductProcessReport.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://doc.volcore.xyz/docs/view-grid、https://doc.volcore.xyz/docs/web
 -->
<template>
    <div class="right">
        <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
            :editFormOptions="editFormOptions" :searchFormFields="searchFormFields"
            :searchFormOptions="searchFormOptions" :table="table" :extend="extend" :onInit="onInit" :onInited="onInited"
            :searchBefore="searchBefore" :searchAfter="searchAfter" :addBefore="addBefore" :addAfter="addAfter"
            :updateBefore="updateBefore" :delAfter="delAfter" :auditModelOpenBefore="auditModelOpenBefore"
            :delBefore="delBefore" :rowClick="rowClick" :modelOpenBefore="modelOpenBefore"
            :modelOpenAfter="modelOpenAfter">
            <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
            <template #gridHeader>
            </template>
        </view-grid>
    </div>
    <!-- 1、显示引用的其他页面 -->
    <div :class="{ 'stockInRef': isStockIn }">
        <stockIn class="stockInRef" ref="stockInRef"></stockIn>
    </div>
    <div :class="{ 'processInspection': isProcessInspection }">
        <ProcessInspection class="processInspection" ref="processInspectionRef"></ProcessInspection>
    </div>
</template>
<script setup lang="jsx">
import stockIn from './StockIn.vue'
import ProcessInspection from './ProcessInspection.vue'
import extend from "@/extension/mes/mes/ProductProcessReport.jsx";
import viewOptions from './ProductProcessReport/options.js'
import { ref, reactive, getCurrentInstance, watch, onMounted, computed } from "vue";
import { useRoute } from 'vue-router'
const route = useRoute()
const grid = ref(null);
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())

let gridRef;//对应[表.jsx]文件中this.使用方式一样
const stockInRef = ref()
const processInspectionRef = ref()
// 切换方法
const isStockIn = ref(true);
const isProcessInspection = ref(true);

//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;
    gridRef.load = true
    if (route.name == "ProductAssign") {
        gridRef.load = false
    }
    //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
    //更多属性见：https://doc.volcore.xyz/docs/view-grid

    editFormOptions.forEach((x) => {
        x.forEach((item) => {
            //监听输入框事件，给其他字段设置值
            if (item.field == 'QualifyQty' || item.field == 'UnQualifyQty' || item.field == 'ScrapQty') {
                item.onKeyPress = ($e) => {
                    if ($e.keyCode == 13) {
                        console.log('回车事件');
                        return;
                    }
                    setTimeout(() => {
                        editFormFields.ReportQty = (editFormFields.QualifyQty || 0) + (editFormFields.UnQualifyQty || 0) + (editFormFields.ScrapQty || 0)
                    }, 100);
                    //editFormFields.ReportQty = (editFormFields.QualifyQty || 0) + (editFormFields.UnQualifyQty || 0) + (editFormFields.ScrapQty || 0)
                };

            }
        });
    });

}
//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {
    columns.forEach(x => {
        //开启表头过滤
        x.filterData = true;
    })

    if (route.name == "ProductAssign") {
        gridRef.height = 200;
        gridRef.buttons.forEach(button => {
            button.hidden = true
            if (button.name == "删除") {
                button.name = "撤销报工"
                button.hidden = true
            }
        });
    } else if (route.fullPath == "/ProductProcessReport?1=1") {
        gridRef.buttons.splice(3, 0, {
            name: '质检', //按钮名称
            icon: 'el-icon-document', //按钮图标:组件示例->图标
            //primary、success、warning、error、info、text、danger
            type: 'primary',
            plain: true,
            onClick: () => {
                isProcessInspection.value = false;
                processInspectionAdd()
            }
        })
    } else {
        gridRef.buttons.forEach(button => {
            if (button.name == "删除") {
                button.name = "撤销报工"
            } else if (button.name == "新建" || button.name == "编辑") {
                button.hidden = true
            }
        });

        gridRef.buttons.splice(3, 0, {
            name: '生产入库', //按钮名称
            icon: 'el-icon-document', //按钮图标:组件示例->图标
            //primary、success、warning、error、info、text、danger
            type: 'primary',
            plain: true,
            onClick: () => {
                isStockIn.value = false;
                stockInAddOpen()
            }
        })
    }

    //根据是否质检锁定合格数量和不合格数量
    gridRef.getFormOption("IsChecked").onChange = (val, option) => {
        if (val == 0) {
            gridRef.getFormOption("ReportQty").readonly = true
            gridRef.getFormOption("QualifyQty").readonly = false
            gridRef.getFormOption("UnQualifyQty").readonly = false
        } else {
            gridRef.getFormOption("ReportQty").readonly = false
            gridRef.getFormOption("QualifyQty").readonly = true
            gridRef.getFormOption("UnQualifyQty").readonly = true
        }
    }

    //根据作业人员动态显示明细表，填写工时汇报信息
    gridRef.hasDetail = false
    gridRef.getFormOption("WorkerId").onChange = (val, option) => {
        //val选中的值，option下拉框选择，输出看
        //这里可以给其他字段设置或者取值： this.editFormFields.字段
        let priceTypeId = gridRef.editFormFields.PriceTypeId

        if (val.length == 0) {
            gridRef.hasDetail = false
        }
        else {
            gridRef.hasDetail = true

            gridRef.getTable("WorkHourReport").rowData.forEach(row => {
                let isDel = true
                val.forEach(item => {
                    if (item == row.WorkerId) {
                        isDel = false
                    }
                })
                if (isDel) {
                    gridRef.getTable('WorkHourReport').toggleRowSelection(row);
                    gridRef.getTable("WorkHourReport").delRow(row)
                }
            });


            val.forEach(item => {
                let isAdd = true
                gridRef.getTable("WorkHourReport").rowData.forEach(row => {
                    if (item == row.WorkerId) {
                        isAdd = false
                    }
                })
                if (isAdd) {

                    //priceTypeId==1计时计价priceTypeId==2计件计价
                    // if (priceTypeId == 1) {
                    //     gridRef.detailOptions.columns.forEach(x => {
                    //         if (x.field == "WorkQtyPrice" || x.field == "WorkQty" || x.field == "WorkHourReportId" || x.field == "ProductProcessReportId") {
                    //             x.hidden = true;//true/false;
                    //         }

                    //         else {
                    //             x.hidden = false;//true/false;
                    //             if (x.field == "WorkHour") {
                    //                 x.require = true;//true/false;
                    //             }
                    //             else {
                    //                 x.require = false;//true/false;
                    //             }
                    //         }
                    //     })
                    // }
                    // else {
                    //     gridRef.detailOptions.columns.forEach(x => {
                    //         if (x.field == "WorkHourPrice" || x.field == "WorkHour" || x.field == "WorkHourReportId" || x.field == "ProductProcessReportId") {
                    //             x.hidden = true;//true/false;
                    //         }
                    //         else {

                    //             x.hidden = false;//true/false;
                    //             if (x.field == "WorkQty") {
                    //                 x.require = true;//true/false;
                    //             }
                    //             else {
                    //                 x.require = false;//true/false;

                    //             }
                    //         }

                    //     })
                    // }

                    gridRef.getTable("WorkHourReport").addRow({
                        WorkerId: item,
                        WorkHour: 0,
                        WorkQty: 0,
                        WorkHourPrice: gridRef.editFormFields.WorkHourPrice,
                        WorkQtyPrice: gridRef.editFormFields.WorkQtyPrice,
                        WorkRate: 1,
                    })
                }
            });

        }
    }


    gridRef.detailOptions.columns.forEach((col) => {
        if (col.field == "WorkHour") {
            if (gridRef.getTable("WorkHourReport") != undefined) {
                col.summary = true
                col.summaryFormatter = (qtyValue, column, rows, summaryArrData) => {
                    gridRef.editFormFields.WorkHourAccount = qtyValue; //TotalQty主表表单的字段
                    return qtyValue;
                };
            }
        }
    });

}

//生成工序检验
const processInspectionAdd = () => {
    let selectRows = gridRef.getSelectRows()
    if (selectRows.length == 0) {
        proxy.$message.error("请选择工序报工记录！");
        return
    }
    if (selectRows[0].AuditStatus == 0 || selectRows[0].AuditStatus == null) {
        proxy.$message.error("该工序报工记录未审核！");
        return
    }

    setTimeout(() => {
        processInspectionRef.value.$refs.grid.editFormFields.ProductProcessReportId = selectRows[0].ProductProcessReportId
        processInspectionRef.value.$refs.grid.editFormFields.ProductProcessReportNo = selectRows[0].BillNo
        processInspectionRef.value.$refs.grid.editFormFields.ProductProcessId = selectRows[0].ProductProcessId
        processInspectionRef.value.$refs.grid.editFormFields.ProductProcessNo = selectRows[0].ProductProcessNo
        processInspectionRef.value.$refs.grid.editFormFields.ProductProcessName = selectRows[0].ProductProcessName
        processInspectionRef.value.$refs.grid.editFormFields.ProductProcessTypeId = selectRows[0].ProductProcessTypeId
        processInspectionRef.value.$refs.grid.editFormFields.DepartmentId = selectRows[0].DepartmentId
        processInspectionRef.value.$refs.grid.editFormFields.ReportQty = selectRows[0].ReportQty
        processInspectionRef.value.$refs.grid.editFormFields.QualifyQty = selectRows[0].QualifyQty
        processInspectionRef.value.$refs.grid.editFormFields.UnQualifyQty = selectRows[0].UnQualifyQty
        processInspectionRef.value.$refs.grid.editFormFields.ScrapQty = selectRows[0].ScrapQty
        processInspectionRef.value.$refs.grid.editFormFields.BillDate = proxy.base.getDate()
        // selectRows.forEach(selectRow => {
        //     processInspectionRef.value.$refs.grid.getTable("ProcessInspectionDetail").addRow({
        //         // MaterialUsedListDetailId: selectRow.MaterialUsedListDetailId,
        //     })
        // })
    }, 400);

    processInspectionRef.value.$refs.grid.add()
}
const searchBefore = async (param) => {
    //界面查询前,可以给param.wheres添加查询参数
    //返回false，则不会执行查询
    if (route.name == "ProductAssign") {
        const assignRows = getAssignSelectRow();
        if (!assignRows.length) {
            param.wheres.push({ name: "ProductAssignId", value: -1 })
        }
        else {
            param.wheres.push({ name: "ProductAssignId", value: assignRows[0].ProductAssignId })
        }
    } else if (route.fullPath == "/ProductProcessReport?1=1") {
        param.wheres.push({ name: "IsInspection", value: 1 })
    }
    return true;
}
const searchAfter = async (rows, result) => {

    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const addAfter = (result) => {  //新建保存后result返回的状态及表单对象
    refreshMainSearch()
    return true;//返回false不会关闭弹出框
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
}
const delBefore = (ids, rows) => { //查询界面的表删除前 ids为删除的id数组,rows删除的行
    let isDeleted = true
    rows.forEach(row => {
        if (row.AuditStatus != 0 && row.AuditStatus != null) {
            isDeleted = false
            proxy.$message.error(row.BillNo + "已审核不允许删除！");
            return isDeleted;
        }
    });
    return isDeleted;//返回false，界面上不会显示
}
const delAfter = (res, rows) => { //查询界面的表删除后方法
    let mainSeletRows = getAssignSelectRow()
    refreshMainSearch()
    return true;
}
const auditModelOpenBefore = (rows, isAnit) => {//审核前
    //rows:审批选中的行数据
    return true;
}
const stockInAddOpen = (row) => {
    let selectRows = gridRef.getSelectRows();
    if (selectRows[0].AuditStatus == 0 || selectRows[0].AuditStatus == null) {
        proxy.$message.error("该通知未审核！");
        return
    }
    if (selectRows[0].IsLasted != 1) {
        proxy.$message.error("该工序报工记录不是末道工序！");
        return
    }
    // if (selectRows[0].IsDipathc == 0 || selectRows[0].IsDipathc == null) {
    //     proxy.$message.error("该通知未启用派工！");
    //     return
    // }
    // if (selectRows.length == 0) {
    //     proxy.$message.error("请选择生产通知！");
    //     return
    // }
    // if (selectRows[0].WaitAssignQty == 0) {
    //     proxy.$message.error("该通知待派工数量为0！");
    //     return
    // }

    var rows = gridRef.getSelectRows()
    let url = 'api/ProductProcessReport/BuildStockInData';

    proxy.http.post(url, rows[0]).then((result) => {

        setTimeout(() => {

            stockInRef.value.$refs.grid.editFormFields.BillDate = proxy.base.getDate()

            stockInRef.value.$refs.grid.editFormFields.DepartmentId = result.departmentId
            stockInRef.value.$refs.grid.editFormFields.ProductProcessReportId = selectRows[0].ProductProcessReportId
            stockInRef.value.$refs.grid.editFormFields.ProductTaskId = result.productTaskId

            console.log(result.stockInDetail)
            result.stockInDetail.forEach(detailRow => {
                stockInRef.value.$refs.grid.getTable("StockInDetail").addRow({
                    MaterialId: detailRow.materialId,
                    MaterialNo: detailRow.materialNo,
                    MaterialName: detailRow.materialName,
                    Spec: detailRow.spec,
                    IsLoted: detailRow.isLoted,
                    Qty: detailRow.qty,
                    Price: detailRow.price,
                    Amount: detailRow.amount
                })
            });


        }, 400);

        stockInRef.value.$refs.grid.add()
    });




}
const rowClick = ({ row, column, event }) => {
    //查询界面点击行事件
    // grid.value.toggleRowSelection(row); //单击行时选中当前行;
    grid.value.clearSelection();
    //点击行默认选中
    grid.value.toggleRowSelection(row); //单击行时选中当前行;
    if (route.name == "ProductAssign") {
        gridRef.buttons.forEach(button => {
            button.hidden = true
            if (button.name == "删除" || button.name == "撤销报工") {
                button.name = "撤销报工"
                button.hidden = false
            }
            if (button.name == "生产入库" && row.IsLasted == 1) {
                button.hidden = false
            }
        });
    }

}
const getAssignSelectRow = () => {
    const fn = proxy.base.getItem('getAssignSelectRow');
    return fn();
}
const refreshMainSearch = (row) => {
    const fn = proxy.base.getItem('mainSearch');
    return fn(row);
}

const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等
    gridRef.detailOptions.buttons.forEach((btn) => {
        btn.hidden = true;
    });
}
//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
<style scoped lang="less">
// 5、默认隐藏引用的页面
.stockInRef ::v-deep(.layout-container) {
    display: none;
}

.processInspection ::v-deep(.layout-container) {
    display: none;
}
</style>
